package com.dk.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.data.Result;
import com.dk.em.ConstantEnum;
import com.dk.entity.TAdminDTO;
import com.dk.pojo.TSpike;
import com.dk.pojo.TSpikeOrder;
import com.dk.service.ITSpikeOrderService;
import com.dk.service.ITSpikeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-30
 */
@RestController
@RequestMapping("/tSpikeController")
@Api(value = "秒杀服务")
public class TSpikeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ITSpikeService itSpikeService;

    @Autowired
    private ITSpikeOrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @ApiOperation(value = "秒杀数量全部数量")
    @GetMapping
    public Result getInfoIdBy() {

        //序列化  只支持 string  hash 类型
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        //查询缓存中所有需要缓存的商品
        List<TSpike> spikeCoods = (List<TSpike>) redisTemplate.boundHashOps("spikeGoods").values();
        if (spikeCoods == null || spikeCoods.size() == 0) {
            //查询秒杀商品

            QueryWrapper Wrapper = new QueryWrapper<TSpike>();
            //库存大于0
            Wrapper.gt("stock_count", 0);
            //审核通过
            Wrapper.eq("status", 1);
            //秒杀时间在开始时间与结束时间之间
            Date date = new Date();
            //当前时间大于开始时间(开始时间小于等于当前时间)
            Wrapper.le("start_time", date);   //le: 小于
            //当前时间小于结束时间(结束时间大于或等于当前时间)
            Wrapper.ge("end_time", date);     //ge: 大于
            spikeCoods = itSpikeService.list(Wrapper);


            //放到redis中
            for (TSpike spike : spikeCoods) {
                redisTemplate.boundHashOps("spikeGoods").put(spike.getId(), spike);
                //将遇见库存单独放到redis中
                redisTemplate.boundValueOps(spike.getId()).set(spike.getStockCount().toString());
            }
        }

        return Result.bulid(ConstantEnum.SUCCESS).setResult(spikeCoods);
    }

    //点击进入抢购商品按钮
    @ApiOperation(value = "进入商品页面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "商品id",required = true,paramType = "path")
    })
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    private Result findById(@PathVariable("id") Long id){
        TSpike tSpike = itSpikeService.getById(id);
        return Result.bulid(ConstantEnum.SUCCESS).setResult(tSpike);
    }

    //点击立即抢购按钮
    @ApiOperation(value = "立即抢购")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "商品id",required = true,paramType = "path"),
            @ApiImplicitParam(name = "token",value = "token值",required = true,paramType = "path")
    })
    @RequestMapping(value = "toSeckill/{id}/{token}",method = RequestMethod.POST)
    public Result toSeckill(@PathVariable("id") Long id, @PathVariable("token") String token){
        //获取用户
        String str = (String) redisTemplate.boundValueOps(token).get();
        TAdminDTO tAdminDTO = JSONObject.parseObject(str, TAdminDTO.class);

        try {
            itSpikeService.createOrder(id,tAdminDTO.getUsername(),tAdminDTO.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.bulid(ConstantEnum.SUCCESS);
    }

    //订单是否生成
    @ApiOperation(value = "获取订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token值",required = true,paramType = "path")
    })
    @RequestMapping(value = "getOrder/{token}",method = RequestMethod.GET)
    public Result getOrder(@PathVariable("token") Long token){

        //获取用户
        String str = (String) redisTemplate.boundValueOps(token).get();
        TAdminDTO tAdminDTO = JSONObject.parseObject(str, TAdminDTO.class);

        Long orderId = (Long) redisTemplate.boundHashOps("orderId").get(tAdminDTO.getUsername());
        if (orderId == null){
            return Result.bulid(ConstantEnum.ERROR);
        }
        return Result.bulid(ConstantEnum.SUCCESS).setResult(orderId);
    }

    //立即支付
    @ApiOperation(value = "立即支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "秒杀商品id",required = true,paramType = "path"),
            @ApiImplicitParam(name = "token",value = "token值",required = true,paramType = "path")
    })
    @RequestMapping(value = "toPay/{id}/{token}",method = RequestMethod.GET)
    public String toPay(@PathVariable("id") Long id,@PathVariable("adminId") String token){

        //获取用户
        String str = (String) redisTemplate.boundValueOps(token).get();
        TAdminDTO tAdminDTO = JSONObject.parseObject(str, TAdminDTO.class);

        QueryWrapper wrapper2 = new QueryWrapper<TSpikeOrder>();
        wrapper2.eq("admin_id",tAdminDTO.getId());
        wrapper2.eq("seckill_id",id);
        TSpikeOrder tspikeOrder = orderService.getOne(wrapper2);

        Message<TSpikeOrder> message = MessageBuilder.withPayload(tspikeOrder).build();
        //发送mq异步延时消息
        rocketMQTemplate.syncSend("seckill",message,3000,16);


        TradeController tradeController = new TradeController();
        String WIDout_trade_no = tspikeOrder.getOutTradeNo();
        String WIDtotal_amount = tspikeOrder.getMoney().toString();
        String WIDsubject = "商品名称";
        String WIDbody = "支付订单";
        String result = tradeController.toAliPay(WIDout_trade_no, WIDtotal_amount, WIDsubject, WIDbody);
        return result;
    }


}